package com.myr.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myr.entity.Users;
import com.myr.service.UserService;
import com.myr.util.JwtUtil;
import com.myr.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author myr
 * @version 1.0
 * @date 2022/11/19 15:55
 */
@RestController
@RequestMapping("user")
@Api(value = "增删改查", tags = "增删改查")
public class UsersController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "按照分页查找", notes = "按照分页查找")
    @GetMapping("findAll")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", required = true),
            @ApiImplicitParam(name = "pageSize", value = "条数", required = true)
    })
    public Result select(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {
        Page<Users> page = userService.selectAll(pageNum, pageSize);
        return new Result(200, "查询成功", page);
    }


    @PostMapping("insert")
    @ApiOperation(value = "添加", notes = "添加")
    public Result insert(@RequestBody Users users) {
        int insert = userService.insert(users);
        return new Result(200, "添加成功");
    }

    @ApiOperation(value = "修改", notes = "修改")
    @ResponseBody
    @PutMapping("update")
    public Result update(@RequestBody Users users) {
        int update = userService.update(users);
        return new Result(200, "修改成功");
    }

    @ApiOperation(value = "删除", notes = "删除")
    @ApiImplicitParam(name = "id", value = "主键", required = true)
    @DeleteMapping("delete")
    public Result delete(Integer id) {
        int delete = userService.delete(id);
        return new Result(200, "删除成功");
    }

    @ApiOperation(value = "登录", notes = "登录")
    @ResponseBody
    @GetMapping("login")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "用户名", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true)
    })
    public Result login(String userName, String password) {
        Users login = userService.login(userName, password);
        System.out.println("login = " + login);
        if (login != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("userName", login.getUsername());
            map.put("password", login.getPassword());
            map.put("id", login.getId());
            map.put("name", login.getName());
            String token = JwtUtil.createToken(map);
            return new Result(200, "登录成功", token);
        }
        return new Result(400, "登录失败");
    }
}
